package com.zuche.seraph.system.controller;

import com.github.pagehelper.PageInfo;
import com.zuche.seraph.common.AjaxResult;
import com.zuche.seraph.common.HttpStatus;
import com.zuche.seraph.common.TableDataInfo;
import com.zuche.seraph.system.entity.UserBean;
import com.zuche.seraph.system.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (SeraphUser)表控制层
 *
 * @author makejava
 * @since 2021-08-07 19:47:31
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public UserBean selectOne(Integer id) {
        return this.userService.queryById(id);
    }

    /**
     * 新增用户
     */
    @PostMapping("createUser")
    public AjaxResult createUser(@RequestBody UserBean userBean) {
        userBean.setCreateTime(new Date());
        userBean.setModifyTime(new Date());
        return toAjax(userService.insert(userBean));
    }

    /**
     * 修改用户
     */
    @PostMapping("updateUser")
    public AjaxResult updateUser(@RequestBody UserBean userBean) {
        userBean.setModifyTime(new Date());
        return toAjax(userService.update(userBean));
    }

    /**
     * 删除用户
     */
    @GetMapping("deleteUser/{id}")
    public AjaxResult deleteUser(@PathVariable String id) {
        userService.deleteById(Integer.parseInt(id));
        return AjaxResult.success();
    }

    /**
     * 用户列表
     */
    @PostMapping("userList")
    public TableDataInfo userList(@RequestBody UserBean userBean) {
        List<UserBean> list = userService.queryAllByCondition(userBean);
        Integer count = userService.queryCount(userBean);
        return getDataTable(list, count);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list, Integer total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows){
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
